from networkx import is_tree # type: ignore
from flask_restful import Resource,reqparse # type: ignore
from flask import request

from flask_shop import models
from flask_shop import db
from flask_shop.category import cate_api

class Categorys(Resource):
    def get(self):
        level = request.args.get('level')
        pnum = request.args.get('pnum')
        psize = request.args.get('psize')
        if level:
            level = int(level)
        else:
            level = 3
        #获取所有的分类信息
       
        base_query = models.Category.query.filter(models.Category.level == 1)
        if all([pnum,psize]):
            cates = base_query.paginate(page=int(pnum),per_page=int(psize))
        else:
            cates = base_query.all()
        #定义一个列表，用于储存所有的分类信息
        cate_list = self.to_tree(cates,level)
        return {'status':200,'msg':'获取分类成功','data':cate_list}

    def to_tree(self,info:list,level): #level=2
        #定义一个空列表，用于存储所有的信息分类
        info_list = []
        #遍历所有的信息分类
        for i in info:
            i_dict = i.to_dict()
            if i.level < level:
               # 获取所有一级分类下的所有二级分类
               i_dict['children'] = self.ti=is_tree(i.children,level)
            info_list.append(i.dict)
        return info_list

    

    def post(self):
        try:
            #创建一个ReuqestParser对象
            parser = reqparse.RequestParser()
            #添加参数
            parser.add_argument('name', type=str, required=True)
            parser.add_argument('level', type=int, required=True)
            parser.add_argument('pid', type=int)
            # 解析参数
            args = parser.parse_args()
            # 判断pid是否传递
            if args.get('pid'):
                c = models.Category(Name=args.get('name'), level=args.get('level'), pid=args.get('pid'))
            else:
                c = models.Category(Name=args.get('name'), level=args.get('level'))
            # 保存到数据库 
            db.session.add(c)
            db.session.commit()
            return {'status':200,'msg':'添加分类成功'}
        except Exception as e:
            print(e)
            return {'status':500,'msg':'添加分类成功'}

cate_api.add_resource(Categorys,'/categorys/')